package e.g;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.roundface.model.Tabel;
import org.roundface.util.ConnetionUtils;

import com.alibaba.fastjson.JSON;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * <p>Title: GeneratorUtil</p>
 * <p>Description: 项目自动生成工具</p>
 * <p>Email: yuyue_qty@163.com</p>
 * @author 晴天雨
 * @date 2016年8月22日下午12:50:40
 * @version 1.0
 */
public class GeneratorUtil {

    //获取模板
    private static Configuration cfg;
    //获取数据库连接
    private static Connection jdbcConnection;
    //数据类型
    private static String[] types = { "TABLE" };
    
    private static final String daoPostfix = "Dao";
    private static final String servicePostfix = "Service";
    private static final String serviceImplPostfix = "ServiceImpl";
    private static final String controllerPostfix = "Controller";
    private static final String mapperPostfix = "Mapper";
    
    @SuppressWarnings("deprecation")
    public static void generator(ObjectVo object){
        try {
            cfg = new Configuration();
            cfg.setClassForTemplateLoading(GeneratorUtil.class, "/templates");
            jdbcConnection = ConnetionUtils.getConnetion();
            String tableName = object.getTableName();
            
            List<Tabel> tables = ConnetionUtils.getTables(jdbcConnection, types, tableName);
            
            for(Tabel table:tables){
                System.out.println(JSON.toJSONString(tables));
                generateData(cfg, table, object);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void generateData(Configuration cfg, Tabel table, ObjectVo object) throws Exception {
        
        /*************************entity*********************************/
        Template temp = cfg.getTemplate("model_temp.ftl");
        String outdir = getPath() + "/data/" + object.getJavaPhysicsPath() + "entity/" + object.getModuleName();
        String outfile = table.getClassName() + ".java";
        generate(table, object, temp, outfile, outdir);
        /*************************dao*********************************/
        temp = cfg.getTemplate("dao_temp.ftl");
        outdir = getPath() + "/data/" + object.getJavaPhysicsPath() + "dao/" + object.getModuleName();
        outfile = "I" + table.getClassName() + daoPostfix + ".java";
        generate(table, object, temp, outfile, outdir);
        /*************************service*********************************/
        temp = cfg.getTemplate("service_temp.ftl");
        outdir = getPath() + "/data/" + object.getJavaPhysicsPath() + "service/" + object.getModuleName();
        outfile = "I" + table.getClassName() + servicePostfix + ".java";
        generate(table, object, temp, outfile, outdir);
        /*************************serviceImpl*********************************/
        temp = cfg.getTemplate("serviceImpl_temp.ftl");
        outdir = getPath() + "/data/" + object.getJavaPhysicsPath() + "service/impl/" + object.getModuleName();
        outfile = table.getClassName() + serviceImplPostfix + ".java";
        generate(table, object, temp, outfile, outdir);
        /*************************controller*********************************/
        temp = cfg.getTemplate("controller_temp.ftl");
        outdir = getPath() + "/data/" + object.getJavaPhysicsPath() + "controller/" + object.getModuleName();
        outfile = table.getClassName() + controllerPostfix + ".java";
        generate(table, object, temp, outfile, outdir);
        /*************************mapper*********************************/
        temp = cfg.getTemplate("mapper_temp.ftl");
        outdir = getPath() + "/data/" + object.getMapperPhysicsPath() ;
        outfile = table.getClassName() + mapperPostfix + ".xml";
        generate(table, object, temp, outfile, outdir);
        
    }
    
    public static void generateListJsp(Configuration cfg, Tabel t, String domain, ObjectVo object)
            throws Exception {

        String path = getPath();
        Template temp = cfg.getTemplate("list_jsp_temp.ftl");
        String outdir = path + "/views/" + domain + "/" + t.getVarName() + "/";
        String outfile = "list.jsp";
        generate(domain, t, temp, outfile, outdir, object);

        Template temp1 = cfg.getTemplate("info_jsp_temp.ftl");
        String outfile1 = "info.jsp";
        generate(domain, t, temp1, outfile1, outdir, object);

        Template temp2 = cfg.getTemplate("form_jsp_temp.ftl");
        String outfile2 = "form.jsp";

        generate(domain, t, temp2, outfile2, outdir, object);
    }

    private static void generate(String domain, Tabel t, Template temp, String outfilename,
            String outdir, ObjectVo object) throws Exception {
        File f = new File(outdir);
        f.mkdirs();
        File fn = new File(f.getPath() + "/" + outfilename);
        fn.createNewFile();
        FileOutputStream fos = new FileOutputStream(fn);
        Writer out = new OutputStreamWriter(fos);
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("table", t);
        root.put("domain", domain);
        temp.process(root, out);
        out.flush();
        out.close();
    }

    private static void generate(Tabel t, ObjectVo object , Template temp, String outfile, String outdir) throws Exception {

        File f = new File(outdir);
        f.mkdirs();

        File fn = new File(f.getPath() + "/" + outfile);
        fn.createNewFile();
        FileOutputStream fos = new FileOutputStream(fn);
        Writer out = new OutputStreamWriter(fos);
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("table", t);
        root.put("object", object);
        root.put("str", "#{");
        root.put("str$", "${");
        root.put("end", "}");
        temp.process(root, out);
        out.flush();
        out.close();
    }
    
    private static String getPath() {
        String path = GeneratorUtil.class.getResource("/").getPath();

        File s = new File(path).getParentFile();
        String n = s.getPath() + "/out/";
        File f = new File(n);
        if (f.exists()) {
            f.delete();
        }
        return f.getPath();
    }
    
}
